from collections import OrderedDict
import os

def find_toml_files(directory="."):
    toml_files = []
    for filename in os.listdir(directory):
        if filename.endswith(".toml"):
            toml_files.append(os.path.join(directory, filename))
    return toml_files

def delete_file(file_path):
    try:
        os.remove(file_path)
        print(f"{file_path} has been deleted.")
    except OSError as e:
        print(f"Error deleting {file_path}: {e}")

def read_from_toml_file(file_path):
    with open(file_path, 'r') as file:
        current_list = []
        for line in file:
            line = line.strip()
            if (len(line) == 0):
                continue
            if (line == versions):
                current_list = versions_list
                continue
            if (line == libraries):
                current_list = libraries_list
                continue
            if (line == plugins):
                current_list = plugins_list
                continue
            current_list.append(line.strip())

def write_to_toml_file(file_path):
    with open(file_path, 'w') as file:
        for item in versions_list:
            file.write(item + '\n')
        file.write('\n')
        for item in libraries_list:
            file.write(item + '\n')
        file.write('\n')
        for item in plugins_list:
            file.write(item + '\n')

# 定义临时数据集合
versions = "[versions]"
libraries = "[libraries]"
plugins = "[plugins]"

versions_list = [versions]
libraries_list = [libraries]
plugins_list = [plugins]

current_directory = os.getcwd() + "/versions"
versionsTomlFile = current_directory + "/versions.toml"

# 删除以前生成的toml文件
delete_file(versionsTomlFile)

# 搜索指定目录的toml文件
toml_files = find_toml_files(current_directory)

# 读取每一个文件的内容，并写入到新的文件中
for item in toml_files:
    read_from_toml_file(item)
    write_to_toml_file(versionsTomlFile)
